package pl.freetimetool.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import pl.freetimetool.domain.Account;
import pl.freetimetool.domain.HolidayRequest;

public class HolidayRequestDaoImpl implements HolidayRequestDao {

	@PersistenceContext
	EntityManager entityManager;

	public HolidayRequest findHolidayRequest(final Integer id) {

		return this.entityManager.find(HolidayRequest.class, id);

	}

	public void addHolidayRequest(final HolidayRequest holidayRequest) {

		this.entityManager.persist(holidayRequest);
	}

	public void deleteHolidayRequest(final Integer id) {

		final HolidayRequest holidayRequest = this.findHolidayRequest(id);
		if (holidayRequest != null) {
			this.entityManager.remove(holidayRequest);
		}

	}

	public Collection<HolidayRequest> listHolidayRequests(final Account account) {

		List<HolidayRequest> holidayList = new ArrayList<HolidayRequest>();

		final CriteriaBuilder cb = this.entityManager.getCriteriaBuilder();
		final CriteriaQuery<HolidayRequest> c = cb.createQuery(HolidayRequest.class);
		final Root<HolidayRequest> r = c.from(HolidayRequest.class);

		c.select(r).where(cb.equal(r.get("account"), account));
		holidayList = this.entityManager.createQuery(c).getResultList();

		return holidayList;

	}

	public List<HolidayRequest> findAllHolidayRequest() {
		return this.entityManager.createQuery("SELECT a FROM HolidayRequest a", HolidayRequest.class).getResultList();
	}

}
